#include "audiocaptureservice.h"
#include <QDebug>
#include <QDir>
#include <QCoreApplication>
#include <QStandardPaths>
#include "config.h"

AudioCaptureService::AudioCaptureService(QObject *parent)
    : QObject(parent)
    , m_audioCapture(nullptr)
    , m_wasapiCapture(nullptr)
    , m_configManager(nullptr)
    , m_reconnectTimer(nullptr)
    , m_statusTimer(nullptr)
    , m_isConnected(false)
    , m_totalBytesSent(0)
    , m_packetsSent(0)
{
    // 创建配置管理器
    m_configManager = new ConfigManager(this);
    
    // 创建音频捕获器
    m_audioCapture = new AudioCapture(this);
    m_wasapiCapture = new WasapiLoopbackCaptureSimple(this);
    
    // 连接信号
    connect(m_audioCapture, &AudioCapture::captureStatusChanged,
            this, &AudioCaptureService::onCaptureStatusChanged);
    connect(m_audioCapture, &AudioCapture::captureError,
            this, &AudioCaptureService::onCaptureError);
    connect(m_audioCapture, &AudioCapture::transmissionStatusChanged,
            this, &AudioCaptureService::onTransmissionStatusChanged);
    connect(m_audioCapture, &AudioCapture::transmissionError,
            this, &AudioCaptureService::onTransmissionError);
    connect(m_audioCapture, &AudioCapture::transmissionDataSent,
            this, &AudioCaptureService::onTransmissionDataSent);
    connect(m_audioCapture, &AudioCapture::transmissionConnectionEstablished,
            this, &AudioCaptureService::onTransmissionConnectionEstablished);
    connect(m_audioCapture, &AudioCapture::transmissionConnectionLost,
            this, &AudioCaptureService::onTransmissionConnectionLost);
    
    // 连接WASAPI捕获器信号
    connect(m_wasapiCapture, &WasapiLoopbackCaptureSimple::captureStatusChanged,
            this, &AudioCaptureService::onCaptureStatusChanged);
    connect(m_wasapiCapture, &WasapiLoopbackCaptureSimple::captureError,
            this, &AudioCaptureService::onCaptureError);
    connect(m_wasapiCapture, &WasapiLoopbackCaptureSimple::transmissionStatusChanged,
            this, &AudioCaptureService::onTransmissionStatusChanged);
    connect(m_wasapiCapture, &WasapiLoopbackCaptureSimple::transmissionError,
            this, &AudioCaptureService::onTransmissionError);
    connect(m_wasapiCapture, &WasapiLoopbackCaptureSimple::transmissionDataSent,
            this, &AudioCaptureService::onTransmissionDataSent);
    connect(m_wasapiCapture, &WasapiLoopbackCaptureSimple::transmissionConnectionEstablished,
            this, &AudioCaptureService::onTransmissionConnectionEstablished);
    connect(m_wasapiCapture, &WasapiLoopbackCaptureSimple::transmissionConnectionLost,
            this, &AudioCaptureService::onTransmissionConnectionLost);
    
    // 创建重连定时器
    m_reconnectTimer = new QTimer(this);
    m_reconnectTimer->setSingleShot(true);
    connect(m_reconnectTimer, &QTimer::timeout, this, &AudioCaptureService::attemptReconnect);
    
    // 创建状态更新定时器
    m_statusTimer = new QTimer(this);
    connect(m_statusTimer, &QTimer::timeout, this, &AudioCaptureService::updateStatus);
    m_statusTimer->start(AudioConfig::STATUS_UPDATE_INTERVAL);
    
    qDebug() << "=== 音频捕获服务启动 ===";
    qDebug() << "配置文件:" << m_configManager->getConfigFilePath();
    qDebug() << "保存到文件:" << (m_configManager->getSaveToFile() ? "是" : "否");
    if (m_configManager->getSaveToFile()) {
        qDebug() << "输出文件路径:" << m_configManager->getOutputFilePath();
    }
    qDebug() << "默认配置:";
    qDebug() << "  服务器地址:" << AudioConfig::DEFAULT_HOST << ":" << AudioConfig::DEFAULT_PORT;
    qDebug() << "  音频格式:" << AudioConfig::SAMPLE_RATE << "Hz," 
             << AudioConfig::CHANNEL_COUNT << "通道," << AudioConfig::SAMPLE_SIZE << "位PCM";
    qDebug() << "  传输频率:" << (1000 / AudioConfig::TRANSMISSION_INTERVAL) << "fps";
    qDebug() << "  缓冲区大小:" << (AudioConfig::BUFFER_SIZE / 1024) << "KB";
    qDebug() << "========================";
}

AudioCaptureService::~AudioCaptureService()
{
    stop();
    
    if (m_reconnectTimer) {
        m_reconnectTimer->stop();
        delete m_reconnectTimer;
    }
    
    if (m_statusTimer) {
        m_statusTimer->stop();
        delete m_statusTimer;
    }
}

void AudioCaptureService::start()
{
    qDebug() << "正在启动音频捕获服务...";
    
    // 始终启动音频捕获，不依赖于传输的成功
    startAudioCapture();
    
    // 尝试启动音频传输（可选）
    startTransmission();
}

void AudioCaptureService::stop()
{
    qDebug() << "正在停止音频捕获服务...";
    
    if (m_wasapiCapture && m_wasapiCapture->isCapturing()) {
        m_wasapiCapture->stopCapture();
    }
    
    if (m_audioCapture && m_audioCapture->isCapturing()) {
        m_audioCapture->stopCapture();
    }
    
    if (m_wasapiCapture) {
        m_wasapiCapture->stopTransmission();
    }
    
    if (m_audioCapture) {
        m_audioCapture->stopTransmission();
    }
    
    qDebug() << "音频捕获服务已停止";
}

void AudioCaptureService::showConfiguration() const
{
    m_configManager->showCurrentConfig();
}

void AudioCaptureService::reloadConfiguration()
{
    qDebug() << "重新加载配置文件...";
    m_configManager->loadConfiguration();
    m_configManager->showCurrentConfig();
}

void AudioCaptureService::onCaptureStatusChanged(bool isCapturing)
{
    if (isCapturing) {
        qDebug() << "✓ 音频捕获已启动";
    } else {
        qDebug() << "✗ 音频捕获已停止";
    }
}

void AudioCaptureService::onCaptureError(const QString &error)
{
    qWarning() << "音频捕获错误:" << error;
}

void AudioCaptureService::onTransmissionStatusChanged(bool isTransmitting)
{
    if (isTransmitting) {
        qDebug() << "✓ 音频传输已启动";
    } else {
        qDebug() << "✗ 音频传输已停止";
    }
}

void AudioCaptureService::onTransmissionError(const QString &error)
{
    qWarning() << "音频传输错误:" << error;
    // 启动重连定时器
    m_reconnectTimer->start(AudioConfig::ERROR_RECONNECT_DELAY);
}

void AudioCaptureService::onTransmissionDataSent(qint64 bytesSent)
{
    m_totalBytesSent += bytesSent;
    m_packetsSent++;
}

void AudioCaptureService::onTransmissionConnectionEstablished()
{
    qDebug() << "✓ 已连接到服务器" << AudioConfig::DEFAULT_HOST << ":" << AudioConfig::DEFAULT_PORT;
    m_isConnected = true;
}

void AudioCaptureService::onTransmissionConnectionLost()
{
    qWarning() << "✗ 与服务器连接断开";
    m_isConnected = false;
    // 启动重连定时器
    m_reconnectTimer->start(AudioConfig::RECONNECT_DELAY);
}

void AudioCaptureService::attemptReconnect()
{
    if (!m_isConnected) {
        qDebug() << "尝试重新连接服务器...";
        startTransmission();
    }
}

void AudioCaptureService::updateStatus()
{
    QString statusInfo = "=== 音频捕获服务状态 ===\n";
    
    // 音频捕获状态
    if (m_wasapiCapture && m_wasapiCapture->isCapturing()) {
        statusInfo += "✓ 音频捕获: 运行中\n";
    } else {
        statusInfo += "✗ 音频捕获: 已停止\n";
    }
    
    // 音频传输状态
    if (m_isConnected) {
        statusInfo += QString("✓ 音频传输: 已连接 | 传输数据: %1 字节 | 数据包: %2\n")
                        .arg(m_totalBytesSent).arg(m_packetsSent);
    } else {
        statusInfo += "✗ 音频传输: 未连接，正在尝试重连...\n";
    }
    
    statusInfo += "========================";
    qDebug() << statusInfo;
}

void AudioCaptureService::startTransmission()
{
    qDebug() << "正在启动音频传输...";
    
    // 使用配置文件中的参数启动传输
    if (m_wasapiCapture->startTransmission(AudioConfig::DEFAULT_HOST, AudioConfig::DEFAULT_PORT)) {
        m_wasapiCapture->setTransmissionEnabled(true);
        qDebug() << "音频传输启动成功";
    } else {
        qWarning() << "启动音频传输失败，将在稍后重试";
        // 启动重连定时器，稍后重试
        m_reconnectTimer->start(AudioConfig::ERROR_RECONNECT_DELAY);
    }
}

void AudioCaptureService::startAudioCapture()
{
    qDebug() << "正在启动音频捕获...";
    
    bool captureStarted = false;
    
    if (m_configManager->getSaveToFile()) {
        QString outputPath = m_configManager->getOutputFilePath();
        
        // 如果输出路径为空，使用默认路径
        if (outputPath.isEmpty()) {
            outputPath = m_configManager->getDefaultOutputPath();
        }
        
        // 确保输出目录存在
        QFileInfo fileInfo(outputPath);
        QDir().mkpath(fileInfo.absolutePath());
        
        if (m_wasapiCapture->startCapture(outputPath)) {
            qDebug() << "音频捕获启动成功，输出文件:" << outputPath;
            captureStarted = true;
        } else {
            qWarning() << "音频捕获启动失败，尝试不保存文件模式...";
            // 如果保存文件模式失败，尝试不保存文件模式
            if (m_wasapiCapture->startCapture("")) {
                qDebug() << "音频捕获启动成功（仅传输模式，不保存文件）";
                captureStarted = true;
            } else {
                qWarning() << "音频捕获启动完全失败";
            }
        }
    } else {
        // 不保存文件，只进行传输
        if (m_wasapiCapture->startCapture("")) {
            qDebug() << "音频捕获启动成功（仅传输模式，不保存文件）";
            captureStarted = true;
        } else {
            qWarning() << "音频捕获启动失败";
        }
    }
    
    if (captureStarted) {
        qDebug() << "✓ 音频捕获服务已启动，将开始捕获系统音频";
    } else {
        qWarning() << "✗ 音频捕获服务启动失败，请检查音频设备配置";
    }
}
